﻿/// <reference path = "Base.ts" />
namespace VantCellTypes {

    interface TimelineCellTypeParam {
        DefaultValue: any;
        direction: string;
        activeIcon: Icon;
        activeColor: string;
        inactiveIcon: Icon;
        inactiveColor: string;
        finishIcon: Icon;
        options: any;
        bindingOptions: any;
        useBinding: boolean;
        placement: "top" | "bottom";
        format: string;
    }

    export class TimelineCellType extends VantCellTypeBase<TimelineCellTypeParam> {
        public onPageLoaded(info: Forguncy.Plugin.CellTypeInfo) {
            const self = this;
            const cellType = this.cellType;
            $(`#${this.uId}`).css("overflow-y", "auto");
            const option = {
                template: `
<van-steps
    :active="active"
    :direction="direction"
    :active-icon="activeIcon"
    :active-color="activeColor"
    :inactive-icon="inactiveIcon"
    :inactive-color="inactiveColor"
    :finish-icon="finishIcon"
>
    <van-step
        :key="key"
        v-for="({ key, title, timestamp }) in stepsOptions"
>
        <p style="margin: 0;">{{ placement === "bottom" ? (title || "") : timestamp }}</p>
        <p style="margin: 0;">{{ placement === "bottom" ? timestamp : (title || "") }}</p>
    </van-step>
</van-steps>
`,
                data() {
                    return {
                        ...self.getDefaultData(),
                        ...cellType,
                        ...self.convertToCssColor(cellType),
                        activeIcon: "checked",
                        inactiveIcon: "",
                        finishIcon: ""
                    };
                },
                computed: {
                    stepsOptions({ useBinding, bindingOptions, options }) {
                        const stepsOptions = useBinding ? bindingOptions : options;
                        return self.isEmpty(stepsOptions) || !Array.isArray(stepsOptions)
                            ? []
                            : self.uniqueKeyCreator(stepsOptions.map(this.formatOption), "value");
                    }
                },
                methods: {
                    getValue() {
                        return this.value;
                    },
                    setValue(value: any) {
                        this.value = value;
                        this.updateActive();
                    },
                    setOptions(options) {
                        if (this.useBinding) {
                            this.bindingOptions = options;
                        } else {
                            this.options = options;
                        }
                        this.updateActive();
                    },
                    updateActive() {
                        // 这里认为字符串数字与数字等价，双等号不能去掉
                        // eslint-disable-next-line
                        const index = this.stepsOptions.findIndex(step => step.value == this.value);
                        if (index > -1) {
                            this.active = index;
                            return;
                        }
                        if (this.value || this.value === 0) {
                            this.active = this.stepsOptions.length;
                        } else {
                            this.active = -1;
                        }
                    },
                    formatOption(stepOption: any) {

                        const { timestamp } = stepOption;

                        const isNumber = typeof (timestamp) === "number" || !isNaN(Number(timestamp));

                        const getDate = (isOADate = true) => {

                            if (isOADate) {

                                const date = Forguncy.ConvertOADateToDate(<number>timestamp);

                                const isInvalidDate = isNaN(date.getTime());

                                return isInvalidDate ? getDate(false) : date;
                            }

                            const dateString = isNumber ? Number(timestamp) : (<string>timestamp)?.replace(/-/g, "/");

                            return new Date(dateString);
                        };

                        const date = getDate();

                        const newTimestamp = self.isValidDate(date)
                            ? self.formatDate(date, cellType.format || "yyyy/MM/dd")
                            : timestamp;

                        return {
                            value: stepOption.value,
                            title: stepOption.title,
                            timestamp: newTimestamp
                        };
                    }
                }
            };

            this.createVueApp(option);

            IconHelper.getIcon(cellType.activeIcon, icon => {
                this.vue.activeIcon = icon;
            });
            IconHelper.getIcon(cellType.inactiveIcon, icon => {
                this.vue.inactiveIcon = icon;
            });
            IconHelper.getIcon(cellType.finishIcon, icon => {
                this.vue.finishIcon = icon;
            });

            this.ReloadBindingItems();

            super.onPageLoaded(info);
        }

        private getDefaultData() {
            return {
                active: -1,
                value: null,
                direction: "vertical",
                useBinding: false,
                options: [],
                bindingOptions: [],
                DefaultValue: ""
            };
        }

        private convertToCssColor(cellType: TimelineCellTypeParam): any {
            const result: any = {};
            result.activeColor = Forguncy.ConvertToCssColor(cellType.activeColor);
            result.inactiveColor = Forguncy.ConvertToCssColor(cellType.inactiveColor);
            return result;
        }

        public reload() {
            this.ReloadBindingItems();
        }

        public ReloadBindingItems() {
            const cellType = this.cellType;
            if (cellType.useBinding) {
                SupportDataSourceCellType.refreshData(this, cellType.bindingOptions, dataSource => this.setDataSource(dataSource));
            }
        }

        public setDataSource(dataSource: any) {
            return this.vue.setOptions(dataSource);
        }

        // runtime methods
        public SetJSONDataSource(
            jsonSource: string,
            valueProperty: string,
            titleProperty: string,
            timestampProperty: string
        ) {
            const isExistEmptyParamter =
                [
                    jsonSource,
                    valueProperty,
                    titleProperty,
                    timestampProperty
                ].some(param => this.isEmpty(param));
            if (!isExistEmptyParamter) {
                let dataSource = JSON.parse(jsonSource);
                dataSource = dataSource.map(data => {
                    return {
                        value: data[valueProperty],
                        title: data[titleProperty],
                        timestamp: data[timestampProperty]
                    };
                });
                this.setDataSource(dataSource);
            }
        }

        public UpdateActiveIcon(activeIcon: Icon) {
            IconHelper.getIcon(activeIcon, icon => {
                this.vue.activeIcon = icon;
            });
        }

        public UpdateActiveColor(activeColor: string) {
            this.vue.activeColor = Forguncy.ConvertToCssColor(activeColor);
        }
    }
}

Forguncy.Plugin.CellTypeHelper.registerCellType("Vant.CellTypes.Timeline, Vant", VantCellTypes.TimelineCellType);